package cn.clx.basic.service.impl;

import cn.clx.basic.constants.BaseConstant;
import cn.clx.basic.dto.RegisterDto;
import cn.clx.basic.exception.BusinessException;
import cn.clx.basic.service.IVerifyCodeService;
import cn.clx.basic.util.StrUtils;
import cn.clx.basic.util.VerifyCodeUtils;
import cn.clx.user.domain.User;
import cn.clx.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;




    /**
     * 图形验证码实现
     * @param key
     * @return
     */
    @Override
    public String verificationCode(String key) {
        if(!StringUtils.hasLength(key)){
            throw new BusinessException("滚，传的啥");
        }
        //随机生成一个四位数 作为验证码
        String code = StrUtils.getComplexRandomString(4);
        //存放在redis中 设置过期时间
        redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);
        //根据code生成图片并把图片转换成base64的字符串
        String verifyCode = VerifyCodeUtils.VerifyCode(100, 38, code);

        return verifyCode;
    }

    /**
     * 短信验证码发送逻辑
     * @param dto
     */
    @Override
    public void sendSmsCode(RegisterDto dto) {
        String type = dto.getType();
        String phone = dto.getPhone();
        if(type==null){
            throw new BusinessException("type不能为空");
        }
        if(type.equals("register")){
            userRegister(dto);
            String phoneCodekey= BaseConstant.RegisterConstants.REGISTER_SMS_PREFIX+phone; //register:phone
            verifyCode(phoneCodekey);
        }else if(type.equals("binder")){
            //微信短信验证
            if(phone==null){
                throw new BusinessException("参数不能为空");
            }
            String phoneCodekey= BaseConstant.RegisterConstants.WECHAT_SMS_PREFIX+phone; //wechat:phone
            verifyCode(phoneCodekey);
        }
    }

    /**
     * 短信验证码通用
     * @param phoneCodekey
     */
    public void verifyCode(String phoneCodekey){
        Object phonecode = redisTemplate.opsForValue().get(phoneCodekey);
        if(phonecode!=null){
            //现在的时间减去之前存储进去的时间，进行判断，过了60s没有
            Long oldtime = Long.valueOf(phonecode.toString().split(":")[1]);
            if(System.currentTimeMillis()-oldtime<60*1000){
                throw new BusinessException("我的60秒呢。。。。");
            }
            //拿到以前的验证码
            String oldcode = phonecode.toString().split(":")[0];
            //重新设置时间，刷新过期时间，继续用以前的短信验证码
            redisTemplate.opsForValue().set(phoneCodekey,oldcode+":"+System.currentTimeMillis(),3,TimeUnit.MINUTES);
            System.out.println("您的短信验证码是:" + oldcode + ",请在三分钟之内使用");
        }else {
            String code = StrUtils.getComplexRandomString(4);
            redisTemplate.opsForValue().set(phoneCodekey,code+":"+System.currentTimeMillis(),3,TimeUnit.MINUTES);
            System.out.println("您的短信验证码是:" + code + ",请在三分钟之内使用");
           // String phone = phoneCodekey.toString().split(":")[1];
           // SendMsgUtils.SendMessage(phone,"您的短信验证码是:"+code+",请在三分钟之内使用");
        }

    }

    /**
     * 用户手机验证码注册
     * @param dto 参数
     */
    public void userRegister(RegisterDto dto) {
        String imageCodeValue = dto.getImageCodeValue();
        String imageCodeKey = dto.getImageCodeKey();
        String phone = dto.getPhone();
        if (imageCodeKey == null || imageCodeValue == null || phone == null ) {
            throw new BusinessException("请传入参数");
        }
        //通过imageCodeKey拿value值
        Object imagetemp = redisTemplate.opsForValue().get(imageCodeKey);
        if (imagetemp == null) {
            throw new BusinessException("图形验证码已过期，请重新获取");
        }
        if (!imagetemp.toString().equalsIgnoreCase(imageCodeValue)) {
            throw new BusinessException("图形验证码输入错误，请重试");
        }
        User user = userMapper.loadByPhone(phone);
        if (user != null) {
            throw new BusinessException("已存在该用户，请直接登陆");
        }

    }

    /**
     * 最初的版本
     * @param dto
     */
   /* @Override
    public void sendSmsCode(RegisterDto dto) {
        //空校验
        String imageCodeValue = dto.getImageCodeValue();
        String imageCodeKey = dto.getImageCodeKey();
        String phone = dto.getPhone();
        if(imageCodeKey==null||imageCodeValue==null||phone==null||type==null){
            throw new BusinessException("请传入参数");
        }
        //通过imageCodeKey拿value值
        Object imagetemp = redisTemplate.opsForValue().get(imageCodeKey);
        if(imagetemp==null){
            throw new BusinessException("图形验证码已过期，请重新获取");
        }
        if(!imagetemp.toString().equalsIgnoreCase(imageCodeValue)){
            throw new BusinessException("图形验证码输入错误，请重试");
        }
        User user =userMapper.loadByPhone(phone);
        if(user!=null){
            throw new BusinessException("已存在该用户，请直接登陆");
        }
        String phoneCodekey= BaseConstant.RegisterConstants.REGISTER_SMS_PREFIX+phone; //register:phone
        Object phonecode = redisTemplate.opsForValue().get(phoneCodekey);
        if(phonecode!=null){
            //现在的时间减去之前存储进去的时间，进行判断，过了60s没有
            Long oldtime = Long.valueOf(phonecode.toString().split(":")[1]);
            if(System.currentTimeMillis()-oldtime<60*1000){
                throw new BusinessException("我的60秒呢。。。。");
            }
            //拿到以前的验证码
            String oldcode = phonecode.toString().split(":")[0];
            //重新设置时间，刷新过期时间，继续用以前的短信验证码
            redisTemplate.opsForValue().set(phoneCodekey,oldcode+":"+System.currentTimeMillis(),3,TimeUnit.MINUTES);
            System.out.println("您的短信验证码是:" + oldcode + ",请在三分钟之内使用");
        }else {
            String code = StrUtils.getComplexRandomString(4);
            redisTemplate.opsForValue().set(phoneCodekey,code+":"+System.currentTimeMillis(),3,TimeUnit.MINUTES);
            System.out.println("您的短信验证码是:" + code + ",请在三分钟之内使用");
        }

        // SendMsgUtils.SendMessage(phone,"您的短信验证码是:"+code+",请在三分钟之内使用");

    }*/
}
